package z_whiteboard2;
import java.io.*;
import java.net.*;
import java.util.*;

public class ObjectClient extends Thread{
	ObjectInputStream receive = null;
	ObjectOutputStream send = null;
	boolean threadFlag=true;

	ObjectMultiServer oms = null;

	public ObjectClient(ObjectMultiServer oms, Socket s){
		this.oms	= oms;
		try{
			OutputStream os = s.getOutputStream();
			send = new ObjectOutputStream(os);

			InputStream is = s.getInputStream();
			receive = new ObjectInputStream(is);

			start();

		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	public void run(){
		try{
			System.out.println("data receiving...");
			while(threadFlag){
				VData d = (VData)receive.readObject();
				sendMsg(d);
				Thread.sleep(500);
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	public void sendMsg(VData d){
		System.out.println("send");
		if( d.command.equals("login")){
			oms.userList.add(d.user);
			oms.userList.validate();
			logInOutMsg("login");
		}else if( d.command.equals("logout")){
			oms.userList.remove(d.user);
			oms.userList.validate();
		}else{
			try{
				for(int i=0 ; i<oms.v.size() ; i++){
					ObjectClient oc = (ObjectClient)oms.v.get(i);
					oc.send.writeObject(d);
					oc.send.flush();
				}
			}catch(Exception ex){}
		}
	}
	
	public void logInOutMsg(String command){
		VData d = null;
		String tempCommand = null;
		try{
			for(int i=0 ; i<oms.v.size() ; i++){
				ObjectClient oc = (ObjectClient)oms.v.get(i);
				tempCommand = command;
				for(int j=0 ; j< oms.userList.getItemCount() ; j++){
					d =new VData();
					d.command = tempCommand;
					d.user = oms.userList.getItem(j);
					oc.send.writeObject(d);
					tempCommand=command + "s";
				}
				oc.send.flush();
			}		
		}catch(Exception ex){}
	}

}
